import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from IPython.display import display
# 控制止损金额
# 止损金额是指在投资或交易某个资产时，设置的最大允许亏损金额。当资产价格下跌到这个止损价位时，投资者会自动止损出局，以避免进一步的亏损。
def mouse_event(event):
    display('x: {} and y: {}'.format(event.xdata, event.ydata))
# stocks = ['600519.csv', 'AAPL.csv', '腾讯.csv']
def risk_control(stock_codes):
    stocks = [f'data/{code}.csv' for code in stock_codes]
    weights = [0.3, 0.4, 0.3]  # 设置股票的权重
    stop_loss = 0.1  # 设置止损点为10%
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

    for stock in stocks:
        # 读取股票数据文件

        df = pd.read_csv(stock, header=1, names=['股票名称', '股票代码', '日期', '开盘', '收盘', '最高', '最低', '成交量', '成交额', '振幅', '涨跌幅', '涨跌额', '换手率'])
        df['收盘'] = pd.to_numeric(df['收盘'], errors='coerce')
        df['成交量'] = pd.to_numeric(df['成交量'], errors='coerce')
        df['振幅'] = pd.to_numeric(df['振幅'], errors='coerce')
        weights = [pd.to_numeric(w, errors='coerce') for w in weights]

        # 资产配置
        df['投资金额'] = df['收盘'] * df['成交量'] * df['振幅'] * weights[stocks.index(stock)]

        # 风险控制 - 止损点
        df['止损金额'] = df['投资金额'] * (1 - stop_loss)

        # 可视化资金管理和风险控制结果
        fig, ax = plt.subplots(1, 1, figsize=(12, 6))
        length = len(df['日期'])
        ax.xaxis.set_major_locator(ticker.MultipleLocator(base=length / 5))  # 解决X轴密集问题
        plt.plot(df['日期'], df['投资金额'], label='投资金额')
        plt.plot(df['日期'], df['止损金额'], label='止损金额')
        plt.xlabel('日期')
        plt.ylabel('金额')
        plt.title(df['股票名称'][0] + '资金管理与风险控制')
        cid = fig.canvas.mpl_connect('button_press_event', mouse_event)
        plt.legend()
        plt.show()
